package com.rest.dao.impl;

import com.rest.dao.RecipeDao;
import com.rest.entity.Recipe;
import com.rest.util.JDBCUtil;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class RecipeDaoImpl implements RecipeDao {

    @Override
    public List<Recipe> list() {
        Connection connection = JDBCUtil.getConnection();
        String sql = "select * from recipes";
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        List<Recipe> list = new ArrayList<>();
        try {
            statement = connection.prepareStatement(sql);
            resultSet = statement.executeQuery();
            while (resultSet.next()) {
                int recipe_id = resultSet.getInt(1);  // 获取 recipe_id (整数)
                String recipe_name = resultSet.getString(2);  // 获取 recipe_name (字符串)
                String category = resultSet.getString(3);  // 获取 category (字符串)
                byte[] image = resultSet.getBytes(4);  // 获取 image (二进制数据，转换为 byte[])
                String unit = resultSet.getString(5);  // 获取 unit (字符串)
                BigDecimal unit_price = resultSet.getBigDecimal(6);  // 获取 unit_price (BigDecimal 类型来表示价格)
                String cooking_instructions = resultSet.getString(7);  // 获取 cooking_instructions (字符串)
                boolean is_active = resultSet.getBoolean(8);  // 获取 is_active (布尔值)

// 将数据封装成一个 Recipe 对象并添加到列表
                list.add(new Recipe(recipe_id, recipe_name, category, image, unit, unit_price, cooking_instructions, is_active));

            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            JDBCUtil.release(connection, statement, resultSet);
        }
        return list;
    }
}
